<template>
	<view class="edit-page">
		<van-address-edit :area-list="areaList" show-delete show-set-default show-search-result
			:search-result="searchResult" :area-columns-placeholder="['请选择', '请选择', '请选择']" :address-info="AddressInfo"
			@save="onSave" @delete="onDelete" @change-detail="onChangeDetail" />
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		showToast
	} from 'vant';
	import {
		areaList
	} from '@vant/area-data';
	import {
		useStore
	} from 'vuex'
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import api from './../../lib/request.js'
	let list = ref(['请选择', '请选择', '请选择'])
	// 搜索结果
	const searchResult = ref([]);
	const store = useStore()
	let uid = ref(store.state.uid)
	let aid = ref(store.state.aid)

	let AddressInfo = ref({})
	let addr = ref({})
	// 保存
	const onSave = (val) => {
		console.log(val);
		const data = {
			id:aid.value,
			userId: uid.value,
			name: val.name,
			province: val.province,
			city: val.city,
			area: val.areaCode,
			detailedAddress: val.addressDetail,
			iphone: val.tel
		};
		api.update('/address/update',data).then(res=>{
				showToast('已修改地址')
				let {data} = res
				let list = []
				for(let k of data){
					let a = { id: k.id,name:k.name,
					tel:k.iphone,address:`${k.province}${k.city}${k.area}${k.detailedAddress}`}
					list.push(a)
				}
				store.commit('update_addlist',list)
				if (res.code) {
					setTimeout(()=>{
							uni.navigateBack({
								url:'/pages/addr/addr'
							})
					},1500)
				}
			})
		
		
	}

	//id
	onLoad(() => {
		uni.setNavigationBarTitle({
			title: aid.value ? '编辑地址' : '新增地址'
		})
		//编辑
		if (aid.value) {
			api.get(`/address/findAllById/${aid.value}`).then(res => {
				let {
					area,
					city,
					detailedAddress,
					id,
					iphone,
					name,
					province,
					userId
				} = res.data
				addr.value.userId=uid.value
				addr.value.name=name
				addr.value.areaCode = area
				addr.value.province=province,
				addr.value.addressDetail=detailedAddress,
				addr.value.tel=iphone
				let {
					city_list,
					county_list
				} = areaList
				
				AddressInfo.value = addr.value
			})
		}
	})
	
	// 删除
	const onDelete = () => {
		showToast('已删除地址')
		api.del(`/address/delete/${aid.value}`).then(res=>{
			if(res.code){
				uni.navigateTo({
					url:'/pages/addr/addr'
				})
			}
		})
	};
	// 修改详细地址时触发	
	const onChangeDetail = (val) => {
		// console.log(val);
	}
</script>

<style>

</style>